package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.GlideApp;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.helper.NetObserverManager;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.app.api.DeviceImpl;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseLocalConfigBean;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.ui.scan.ScanHelper;
import com.supor.aiot.common.ui.view.DotTextView;
import com.supor.aiot.common.utils.MPLoggerUtils;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.RecipeChefAdapter;
import com.supor.aiot.food.adapter.RecipeDeviceAdapter;
import com.supor.aiot.food.adapter.RecipeHotAdapter;
import com.supor.aiot.food.adapter.RecipeNoneResultAdapter;
import com.supor.aiot.food.adapter.RecipeTopicAdapter;
import com.supor.aiot.food.adapter.RecomondRecipeAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.BindDeviceBean;
import com.supor.aiot.food.bean.ChefDetailBean;
import com.supor.aiot.food.bean.ChildListBean;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecipeStoreBean;
import com.supor.aiot.food.bean.RecipeTopicBean;
import com.supor.aiot.food.databinding.FoodFragmentRootBinding;
import com.supor.aiot.food.utils.DoubleClickUtils;
import com.supor.aiot.food.view.FoodGridItemDecoration;
import com.supor.aiot.food.view.GrideItemDecoration;
import com.supor.aiot.food.view.JumpToVideoInfoLayout;
import com.supor.aiot.food.view.MyItemDecoration;
import com.supor.aiot.food.view.NoWiFiDialog;
import com.supor.aiot.food.view.SelectDevicePopwindow;
import com.supor.md_video.api.VideoApiImpl;
import com.supor.md_video.entity.VideoFavoritBean;
import com.supor.md_video.tools.NumberUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import me.dkzwm.widget.srl.HorizontalSmoothRefreshLayout;
import me.dkzwm.widget.srl.RefreshingListenerAdapter;
import me.dkzwm.widget.srl.indicator.IIndicator;

public class FoodFragment extends BaseMVVMFragment<FoodViewModel, FoodFragmentRootBinding> implements View.OnClickListener {
    public final static int INDEX_IN_HOME = 2;//计数从1开始
    private FoodViewModel mViewModel;
    private List<RecipeTopicBean> mTopicList = new ArrayList<>();
    private List<ChefDetailBean> mCookerList = new ArrayList<>();
    private List<BindDeviceBean> mDeviceList = new ArrayList<>();
    private List<RecipeHotBean> mHotList = new ArrayList<>();
    private List<ChildListBean> mClassifyList = new ArrayList<>();
    private List<ChildListBean> mOriginList = new ArrayList<>();
    private List<ChildListBean> childListBeanList = null;
    private RecomondRecipeAdapter recipeAdapter;
    private RecipeChefAdapter cookerAdapter;
    private RecipeTopicAdapter topicAdapter;
    private RecipeDeviceAdapter deviceAdapter;
    private RecipeHotAdapter hotAdapter;
    private RecipeNoneResultAdapter noneResultAdapter;
    private String deviceProductModel = "";
    private int StatePositon = 1;
    private int originHotPage = 1;
    private int originNewPage = 1;
    private int DevicePosition = 0;
    private String recomondWord;
    private View headerView;
    private ImageView ivRecipeAll;
    private ImageView ivFruitEggs;
    private ImageView ivMainFood;
    private ImageView ivMeatMean;
    private ImageView ivSeaFood;
    private TextView tvFruitEggs;
    private TextView tvMainFood;
    private TextView tvMeatMean;
    private TextView tvSeaFood;
    private TextView edtFoodInput;
    private ImageView ivScan;
    private RecyclerView rvRecordRecipe;
    private RecyclerView rvRecipeClass;
    private RecyclerView rvRecipeCooker;
    private RecyclerView rvRecipeDevice;
    private DotTextView tvRecipeHot;
    private DotTextView tvRecipeNew;
    private View rlNoneResult;
    private LinearLayout llTopicOuter;
    private RelativeLayout rlButtonButtom;
    private StaggeredGridLayoutManager gridLayoutManager;
    private NoWiFiDialog noWiFiDialog;
    private SelectDevicePopwindow selectDevicePopwindow;
    private HorizontalSmoothRefreshLayout mHorizontalRefreshLayout;
    private ImageView ivXunwei;
    private Vibrator vibrator;
    private boolean isHideShowed;
    private LinearLayoutManager rvRecordLayoutManager;
    //    private PullLeftLoadMoreLayout pullLeftLoadMoreLayout;
    //    private SmartRefreshHorizontal smartRefreshHorizontal;

    public static FoodFragment newInstance() {
        return new FoodFragment();
    }

    private static final String CLASSIFY_POSITION = "CLASSIFY_POSITION";
    private static final String CLASSIFY_DATA = "CLASSIFY_DATA";
    private static final String CHEF_ID = "CHEF_ID";
    private static final String RECOMOND_WORD = "RECOMOND_WORD";
    private static final String CLASSIFY_SECOND_DATA = "CLASSIFY_SECOND_DATA";
    private static final String CLASSIFY_SECOND_POSITION = "CLASSIFY_SECOND_POSITION";
    private static final String TAG = "FoodFragment";

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(FoodViewModel.class);
        initRecycleView();
        initCommondClick();
        initOriginState();
        initRxBus();
    }

    private void initRxBus() {
        RxBus3.getInstance().register(Constants.Tag.LOGIN, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                initOriginState();
            }
        }, this.getClass());
        RxBus3.getInstance().register(Constants.Tag.LOGOUT, (Consumer<String>) s -> {
            if (Constants.Value.SUCCESS.equalsIgnoreCase(s)) {
                initOriginState();
            }
        }, this.getClass());
        RxBus3.getInstance().register(Constants.Tag.BINDING_STATUS, (Consumer<String>) s -> {
            initOriginState();
        }, getClass());
    }

    private void netStateNotice() {
        NoWiFiDialog.Builder builder = new NoWiFiDialog.Builder(getActivity());
        builder.setCancelListener(view -> {
            //禁止播放
            noWiFiDialog.dismiss();
        });
        builder.setNetListener(() -> {
            BaseSharedPreferences.setBoolean(getActivity(), Constants.Key.WIFI_PLAY, true);
        });

        builder.setShadow(true);
        builder.setCanCancel(true);
        noWiFiDialog = builder.create();
        noWiFiDialog.show();
    }

    @Override
    public void updateNetStatus(int type) {
        if (type == 0) {
            showError();
        } else {
            if (type != 1)
                ToastUtils.getInstance().showCustomToast(getActivity().getResources().getString(R.string.no_wifi_notice));
            showContentView();
        }
    }


    private void initOriginState() {
        initAllClassify();
        initChefList();
        initDevice();
        initNewRecomond();
        initVedioRecipe();
        initFoodRecomonds();
        deviceProductModel = "";
        isHideShowed = false;
        bindingView.rlButtonHead.setVisibility(View.GONE);
        if (StatePositon == 1) {
            initHotRecipe(deviceProductModel);
        } else {
            initNewRecipe(deviceProductModel);
        }
        bindingView.refreshLayouthead.finishRefresh();
    }

    private void initCommondClick() {
        ivRecipeAll.setOnClickListener(this);
        ivFruitEggs.setOnClickListener(this);
        ivMainFood.setOnClickListener(this);
        ivMeatMean.setOnClickListener(this);
        ivSeaFood.setOnClickListener(this);
        edtFoodInput.setOnClickListener(this);
        ivScan.setOnClickListener(this);
        bindingView.ivHeadSearch.setOnClickListener(this);
        bindingView.rlSelectDevice.setOnClickListener(this);

        bindingView.refreshLayouthead.setOnLoadMoreListener(refreshLayout -> {
            if (StatePositon == 1) {
                originHotPage++;
                initHotRecipe(deviceProductModel);
            } else {
                originNewPage++;
                initNewRecipe(deviceProductModel);
            }
        });

        bindingView.refreshLayouthead.setEnableRefresh(true);
        bindingView.refreshLayouthead.setEnableLoadMore(true);
        bindingView.refreshLayouthead.setOnRefreshListener(refreshLayout -> initOriginState());
        bindingView.refreshLayouthead.setRefreshHeader(new ClassicsHeader(getActivity()));
        bindingView.refreshLayouthead.setRefreshFooter(new ClassicsFooter(getActivity()));

        bindingView.refreshLayouthead.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                refreshLayout.finishLoadMore(2000);
            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                ViewGroup.LayoutParams layoutParams = bindingView.parallax.getLayoutParams();
                layoutParams.height = (int) (getResources().getDimensionPixelOffset(R.dimen.dp_222) + header.getView().getTranslationY());
                bindingView.parallax.setLayoutParams(layoutParams);
            }
        });
    }

    private void initDevice() {
//        getUnbindDevice();
        getAllDevices();
        DevicePosition = 0;
        bindingView.tvSelectedDevice.setText(getActivity().getResources().getString(R.string.total_device_recipes));
        if (selectDevicePopwindow != null) {
            selectDevicePopwindow.setPopDevicePosition(DevicePosition);
            Log.e("nail", "popwindow = 0");
        }
    }

    private void gotoScanActivity() {
        ScanHelper.getInstance().scan(getActivity(), new ScanHelper.ScanCallback() {
            @Override
            public void onScanResult(boolean isProcessed, Intent result) {
                if (!isProcessed) {
                    // 扫码界面点击物理返回键或左上角返回键
                    return;
                }

                // 注意：本回调是在子线程中执行
                getActivity().runOnUiThread(() -> {
                    if (result == null || result.getData() == null) {
                        // 扫码失败
                        return;
                    }
                    // 扫码成功
                    String url = result.getData().toString();
                    Logc.d("scan url: " + url);
                    //initSearch(url);
                    ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.error_scan_result));
                });
            }
        });
    }

    @SuppressLint("AutoDispose")
    private void initHotRecipe(String productModel) {
        SearchFoodImpl.getInstance().getHotRecipeFoodNew(productModel, originHotPage, 10).subscribe(result -> {
            if (result.data.rows.size() == 0) {

                if (isHideShowed) {
                    ViewGroup.LayoutParams layoutParams = rlNoneResult.getLayoutParams();
                    layoutParams.height = RelativeLayout.LayoutParams.MATCH_PARENT;
                    if (bindingView.rvRecipeList.getFooterCount() == 0)
                        bindingView.rvRecipeList.addFooterView(rlNoneResult);
                    bindingView.rvRecipeList.smoothScrollToPosition(2);
                } else {
                    ViewGroup.LayoutParams layoutParams = rlNoneResult.getLayoutParams();
                    layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    if (bindingView.rvRecipeList.getFooterCount() == 0)
                        bindingView.rvRecipeList.addFooterView(rlNoneResult);
                }

                mHotList.clear();
                hotAdapter.notifyDataSetChanged();
                bindingView.refreshLayouthead.setEnableLoadMore(false);
                Logc.e(result.message);
            } else {
                bindingView.refreshLayouthead.setEnableLoadMore(true);
                if (originHotPage == 1) {
                    mHotList.clear();
                }
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                }
                if (bindingView.rvRecipeList.getFooterCount() > 0)
                    bindingView.rvRecipeList.removeFooterView(rlNoneResult);
                hotAdapter.notifyDataSetChanged();
            }
            bindingView.refreshLayouthead.finishLoadMore();
        }, throwable -> {
            Logc.e(throwable.getMessage());
            mHotList.clear();
            if (bindingView.rvRecipeList.getFooterCount() == 0)
                bindingView.rvRecipeList.addFooterView(rlNoneResult);
            hotAdapter.notifyDataSetChanged();
            bindingView.refreshLayouthead.finishLoadMore();
            bindingView.refreshLayouthead.setEnableLoadMore(false);
        });
    }

    @SuppressLint("AutoDispose")
    private void initNewRecipe(String productModel) {
        SearchFoodImpl.getInstance().getRecipeNew(productModel, "new", originNewPage, 10).subscribe(result -> {
            if (result.data.rows.size() == 0) {
                if (isHideShowed) {
                    ViewGroup.LayoutParams layoutParams = rlNoneResult.getLayoutParams();
                    layoutParams.height = RelativeLayout.LayoutParams.MATCH_PARENT;
                    if (bindingView.rvRecipeList.getFooterCount() == 0)
                        bindingView.rvRecipeList.addFooterView(rlNoneResult);
                    bindingView.rvRecipeList.smoothScrollToPosition(2);
                } else {
                    ViewGroup.LayoutParams layoutParams = rlNoneResult.getLayoutParams();
                    layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    if (bindingView.rvRecipeList.getFooterCount() == 0)
                        bindingView.rvRecipeList.addFooterView(rlNoneResult);
                }
                mHotList.clear();
                hotAdapter.notifyDataSetChanged();
                bindingView.refreshLayouthead.setEnableLoadMore(false);
                Logc.e(result.message);
            } else {
                bindingView.refreshLayouthead.setEnableLoadMore(true);
                if (originNewPage == 1) {
                    mHotList.clear();
                }
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                }
                if (bindingView.rvRecipeList.getFooterCount() > 0)
                    bindingView.rvRecipeList.removeFooterView(rlNoneResult);
                hotAdapter.notifyDataSetChanged();
            }
            bindingView.refreshLayouthead.finishLoadMore();
        }, throwable -> {
            Logc.e(throwable.getMessage());
            mHotList.clear();
            if (bindingView.rvRecipeList.getFooterCount() == 0)
                bindingView.rvRecipeList.addFooterView(rlNoneResult);
            hotAdapter.notifyDataSetChanged();
            bindingView.refreshLayouthead.finishLoadMore();
            bindingView.refreshLayouthead.setEnableLoadMore(false);
        });
    }


    @SuppressLint("AutoDispose")
    private void initNewRecomond() {
        recomondWord = getActivity().getResources().getString(R.string.default_recomond);
        SearchFoodImpl.getInstance().getNewRecomond().subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(result.data.rows.get(0).getRecipeName())) {
                    recomondWord = result.data.rows.get(0).getRecipeName();
                    edtFoodInput.setText(recomondWord);
                }
                ;
            } else {
                Logc.e(result.message);
                edtFoodInput.setText(recomondWord);
            }
        }, throwable -> {
            Logc.e(throwable.getMessage());
            edtFoodInput.setText(recomondWord);
        });
    }


    /**
     * 查询所有分类列表
     */
    @SuppressLint("AutoDispose")
    private void initAllClassify() {
        SearchFoodImpl.getInstance().getAllClassify("APP_CLASSIFACTION", 50).subscribe(result -> {
            if (result.isSuccess()) {
                initRecipeClassify(result.data.rows);
                mClassifyList.clear();
                mOriginList.clear();
                mOriginList.addAll(result.data.rows);
                for (int i = 0; i < result.data.rows.size(); i++) {
                    ChildListBean childListBean = result.data.rows.get(i);
                    if (childListBean.getClassificationName().equals(getActivity().getResources().getString(R.string.recipe_devices))) {
                        mClassifyList.add(childListBean);
                    } else {
                        if (childListBean.getChildList().size() > 0) {
                            mClassifyList.add(childListBean);
                        }
                    }
                }
            } else {
                Logc.e(result.message);
            }
        }, throwable -> {
            Logc.e(throwable.getMessage());
        });
    }

    /**
     * 星厨秀
     */
    @SuppressLint("AutoDispose")
    private void initChefList() {
        SearchFoodImpl.getInstance().getChefList(1, 200).subscribe(result -> {
            if (result.isSuccess()) {
                mCookerList.clear();
                mCookerList.addAll(result.data.rows);
                cookerAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.getInstance().showCustomToast(result.message);
            }

        }, throwable -> {
            ToastUtils.getInstance().showCustomToast(throwable.getMessage());
        });
    }


//    @SuppressLint("AutoDispose")
//    private void getUnbindDevice() {
//        SearchFoodImpl.getInstance().getUnbindDevice().subscribe(result -> {
//            if (result.isSuccess()) {
//                mDeviceList.clear();
//                mDeviceList.addAll(result.data);
//                if (mDeviceList.size() == 0) {
//                    rvRecipeDevice.setVisibility(View.GONE);
//                    bindingView.rlSelectDevice.setVisibility(View.GONE);
//                } else {
//                    rvRecipeDevice.setVisibility(View.VISIBLE);
//                    bindingView.rlSelectDevice.setVisibility(View.VISIBLE);
//                    deviceAdapter.notifyDataSetChanged();
//                }
//            } else {
//                Logc.e(TAG, "rsult error" + result.message);
//            }
//
//        }, throwable -> {
//            Logc.e(throwable.getMessage());
//        });
//    }

    @SuppressLint("AutoDispose")
    private void getAllDevices() {
        DeviceImpl.getInstance().getAllDevice(1000).subscribe(result -> {
            List<ProductType> productTypeList = result.data.rows;
            setDeviceList(productTypeList);
        }, throwable -> {
            Logc.e("accept: " + throwable);
            // ToastUtils.getInstance().showCustomToast("获取产品失败");
        });
    }

    private void setDeviceList(List<ProductType> productTypeList) {
        mDeviceList.clear();
        for (ProductType productType : productTypeList) {
            for (ProductType.ProductModel child : productType.Children) {
                BindDeviceBean bindDeviceBean = new BindDeviceBean();
                bindDeviceBean.setModelId(child.modelId);
                bindDeviceBean.setModelTypeName(child.crmModelName);
                bindDeviceBean.setNote(child.note);
                bindDeviceBean.setRemark(child.remark);
                bindDeviceBean.setParentTypeImage(child.modelPicture);
                bindDeviceBean.setBind(child.bindStatus);
                mDeviceList.add(bindDeviceBean);
            }
        }

        if (mDeviceList.size() == 0) {
            rvRecipeDevice.setVisibility(View.GONE);
            bindingView.rlSelectDevice.setVisibility(View.GONE);
        } else {
            rvRecipeDevice.setVisibility(View.VISIBLE);
            bindingView.rlSelectDevice.setVisibility(View.VISIBLE);
        }
        deviceAdapter.notifyDataSetChanged();

        new Handler().postDelayed(() -> {
            if (mDeviceList.size() > 0) {
                // 无论什么情况，第一个设备选中
                deviceAdapter.setPosition(0);

                deviceProductModel = mDeviceList.get(0).getModelId();
                bindingView.tvSelectedDevice.setText(mDeviceList.get(0).getModelTypeName());
                DevicePosition = 1;
                if (selectDevicePopwindow != null)
                    selectDevicePopwindow.setPopDevicePosition(DevicePosition);

                originNewPage = 1;
                originHotPage = 1;
                if (StatePositon == 1) {
                    initHotRecipe(deviceProductModel);
                } else {
                    initNewRecipe(deviceProductModel);
                }
                isHideShowed = false;
//                if (mDeviceList.get(0).isBind() || !AppAgent.isLogin()) {
//
//                }
            }
        }, 500);
    }


    private void initVedioRecipe() {
        if (!isFirstShow) {
            recipeAdapter.stopListPlay();
            getVideoRecipeData();
        } else {
            ArrayList<RecipeHotBean> tpArr = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                RecipeHotBean recipeHotBean = new RecipeHotBean();
                recipeHotBean.setItemType(-1);
                tpArr.add(recipeHotBean);
            }
            recipeAdapter.setList(tpArr);
        }
    }

    @SuppressLint("AutoDispose")
    private void getVideoRecipeData() {
        SearchFoodImpl.getInstance().getVedioRecips(1, 5, "VIDEO", "RELEASE").subscribe(result -> {
            if (result.isSuccess()) {
//                recipeAdapter.stopListPlay();
                if (null != result.data.rows) {
                    ArrayList<RecipeHotBean> tpDataArr = new ArrayList<>();
                    tpDataArr.addAll(result.data.rows);
                    recipeAdapter.setList(tpDataArr);
                }
                if (!isFirstShow) {
                    rvRecordRecipe.removeCallbacks(videoResumeRun);
                    rvRecordRecipe.postDelayed(videoResumeRun, 150);
                }

//                recipeAdapter.onResume();
            } else {
                showError();
            }

        }, throwable -> {
            showError();
        });
    }

    @SuppressLint("AutoDispose")
    private void initFoodRecomonds() {
        SearchFoodImpl.getInstance().getFoodRecords(Constants.Fun.APP_TWO, 200).subscribe(result -> {
            if (result.isSuccess()) {
                mTopicList.clear();
                mTopicList.addAll(result.data.rows);
                if (mTopicList.size() > 0) {
                    llTopicOuter.setVisibility(View.VISIBLE);
                } else {
                    llTopicOuter.setVisibility(View.GONE);
                }
                topicAdapter.notifyDataSetChanged();
            } else {
                Logc.e(result.message);
            }

        }, throwable -> {
            Logc.e(throwable.getMessage());
        });
    }

    /**
     * 收藏食谱
     *
     * @param storeBean
     */
    @SuppressLint("AutoDispose")
    private void setRecipeStored(RecipeStoreBean storeBean) {
        SearchFoodImpl.getInstance().recipeStore(storeBean).subscribe(result -> {
            if (result.isSuccess()) {
                if (StatePositon == 1) {
                    originHotPage = 1;
                    initHotRecipe(deviceProductModel);
                } else {
                    originNewPage = 1;
                    initNewRecipe(deviceProductModel);
                }
            } else {
                Logc.e(result.message);
            }
        }, throwable -> {
            Logc.e(throwable.getMessage());
        });
    }

    /**
     * 取消收藏食谱
     *
     * @param favorateId
     */
    @SuppressLint("AutoDispose")
    private void cancleRecipeStored(int favorateId) {
        SearchFoodImpl.getInstance().cancleRecipeStore(favorateId).subscribe(result -> {
            if (result.isSuccess()) {
                if (StatePositon == 1) {
                    originHotPage = 1;
                    initHotRecipe(deviceProductModel);
                } else {
                    originNewPage = 1;
                    initNewRecipe(deviceProductModel);
                }
            } else {
                Logc.e(result.message);
            }

        }, throwable -> {
            Logc.e(throwable.getMessage());
        });
    }

    private void initVideoList() {
        rvRecordLayoutManager = new LinearLayoutManager(getActivity());
        rvRecordLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvRecordRecipe.setLayoutManager(rvRecordLayoutManager);
        rvRecordRecipe.addItemDecoration(new GrideItemDecoration(getActivity()));
        recipeAdapter = new RecomondRecipeAdapter();
        rvRecordRecipe.setAdapter(recipeAdapter);
        recipeAdapter.bindRecView(rvRecordRecipe);
//        ClassicFooter<IIndicator> footer = new ClassicFooter<>(getContext());
        JumpToVideoInfoLayout<IIndicator> footer = new JumpToVideoInfoLayout<>(getActivity());

        mHorizontalRefreshLayout.setFooterView(footer);
//        mHorizontalRefreshLayout.setDisableRefresh(true);
//        mHorizontalRefreshLayout.setDisableLoadMore(false);
//        mHorizontalRefreshLayout.setDisablePerformLoadMore(false);
//        mHorizontalRefreshLayout.setEnableKeepRefreshView(false);
//        mHorizontalRefreshLayout.setDisableWhenAnotherDirectionMove(true);
        mHorizontalRefreshLayout.setDisableRefresh(true);
        mHorizontalRefreshLayout.setDisableLoadMore(false);
        mHorizontalRefreshLayout.setEnableOverScroll(false);
        vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
        mHorizontalRefreshLayout.setOnRefreshListener(new RefreshingListenerAdapter() {
            @Override
            public void onRefreshing() {
                super.onRefreshing();
            }

            @Override
            public void onLoadingMore() {
                super.onLoadingMore();
//                mHorizontalRefreshLayout.setDurationToClose(500);
//                rvRecordRecipe.scrollToPosition(recipeAdapter.getData().size() - 1);
                vibrator.vibrate(50);
                ARouter.getInstance().build(PathUrl.PATH_MD_VIDEO_LIST)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(FoodFragment.this.getContext());
                mHorizontalRefreshLayout.setDurationToClose(500);
                mHorizontalRefreshLayout.refreshComplete();
            }
        });
//        mHorizontalRefreshLayout.setRatioToKeep(1);
//        mHorizontalRefreshLayout.setRatioToRefresh(1);
//        mHorizontalRefreshLayout.autoRefresh(false);


        viewModel.getRecipeThumbsResult().observe(getActivity(), new Observer<BaseLocalConfigBean>() {
            @Override
            public void onChanged(BaseLocalConfigBean baseLocalConfigBean) {
                if (null != baseLocalConfigBean
                        && recipeAdapter.getData().size() > baseLocalConfigBean.getLocalPosition()) {
                    RecipeHotBean recipeHotBean = recipeAdapter.getData().get(baseLocalConfigBean.getLocalPosition());
                    if (!recipeHotBean.getRecipeId().equals(baseLocalConfigBean.getLocalId())) {
                        return;
                    }
                    recipeHotBean.setLikeId(baseLocalConfigBean.getLocalLikeId());
                    recipeHotBean.setLikeCount(recipeHotBean.getLikeCount() + baseLocalConfigBean.getLocalType());
                    recipeHotBean.setIsLike(baseLocalConfigBean.getLocalType() > 0
                            ? 1 : 2);
                    ImageView ivLike = (ImageView) recipeAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.iv_recipe_like);
                    if (null != ivLike) {
                        ivLike.setBackgroundResource(recipeHotBean.getIsLike() == 1
                                ? R.mipmap.like_icon_clicked : R.mipmap.like_icon_none);
                    }
                    TextView tvThumbNum = (TextView) recipeAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.tv_recipe_like);
                    if (null != tvThumbNum) {
                        tvThumbNum.setText(NumberUtils.formatNum(recipeHotBean.getLikeCount()));
//                        tvThumbNum.setTextColor(recipeHotBean.getIsLike() == 1 ? 0xffff9b00 : 0xff999999);
                    }
                }
            }
        });
        recipeAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (recipeAdapter.getData().size() > position) {

                    if (view.getId() == R.id.iv_recipe_voice) {
                        recipeAdapter.getData().get(position).setLocalIsMuteEnb(recipeAdapter.getData().get(position).getLocalIsMuteEnb()
                                == 1 ? 0 : 1
                        );
                        view.setBackgroundResource(recipeAdapter.getData().get(position).getLocalIsMuteEnb() == 1 ?
                                R.mipmap.play_voice_icon : R.mipmap.play_voice_mute);

                        recipeAdapter.setVolume(position, recipeAdapter.getData().get(position).getLocalIsMuteEnb());
                    } else if (view.getId() == R.id.ll_rep_like) {
                        if (!passClick()) return;
                        if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                            RecipeHotBean recipeHotBean = recipeAdapter.getData().get(position);
                            if (recipeHotBean.getIsLike() == 1) {
                                viewModel.recipeThumbsDel(recipeHotBean.getRecipeId(), recipeHotBean.getLikeId(), position);
                            } else {
                                viewModel.recipeThumb(recipeHotBean.getRecipeId(), position);
                            }
                        } else {
                            ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation(getActivity());
                        }
                    } else if (view.getId() == R.id.ll_rep_sub) {
                        if (!passClick()) return;
                        if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                            Observable<BaseApiResult<VideoFavoritBean>> observable;
                            if (recipeAdapter.getData().get(position).getFavoriteType() == 1) {
                                observable = VideoApiImpl.getInstance().subRecipeDel(String.valueOf(recipeAdapter.getData().get(position).getFavoriteId()));
                            } else {
                                observable = VideoApiImpl.getInstance().subRecipe(recipeAdapter.getData().get(position).getRecipeId(), GlobalDataCache.userInfo.getBossUserId());
                            }
                            observable.subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
//                                .to(autoDisposeConverter)
                                    .subscribe(new Consumer<BaseApiResult<VideoFavoritBean>>() {
                                        @Override
                                        public void accept(BaseApiResult<VideoFavoritBean> stringBaseApiResult) throws Exception {
//                                            FavoritStateBean favoritStateBean = new FavoritStateBean();
//                                            favoritStateBean.setFavoriteId(stringBaseApiResult.data.getFavoriteId());
//                                            favoritStateBean.setId(addrId);
//                                            favoritStateBean.setLocalCountType(1);
//                                            favoritStateBean.setLocalPosition(position);
//                                            favoritResult.setValue(favoritStateBean);
                                            RecipeHotBean recipeHotBean = recipeAdapter.getData().get(position);

                                            if (recipeHotBean.getFavoriteType() == 1) {
                                                recipeHotBean.setFavoriteCount(recipeHotBean.getFavoriteCount() - 1);
                                                recipeHotBean.setFavoriteType(2);
                                                ImageView imageView = (ImageView) recipeAdapter.getViewByPosition(position, R.id.iv_recipe_store);
                                                if (null != imageView) {
                                                    imageView.setBackgroundResource(R.mipmap.ic_recipe_sub_gary);
                                                }
                                            } else {
                                                recipeHotBean.setFavoriteCount(recipeHotBean.getFavoriteCount() + 1);
                                                recipeHotBean.setFavoriteType(1);
                                                recipeHotBean.setFavoriteId(stringBaseApiResult.data.getFavoriteId());
                                                ImageView imageView = (ImageView) recipeAdapter.getViewByPosition(position, R.id.iv_recipe_store);
                                                if (null != imageView) {
                                                    imageView.setBackgroundResource(R.mipmap.stored_icon);
                                                }
                                            }
                                            TextView tvThumbNum = (TextView) recipeAdapter
                                                    .getViewByPosition(position, R.id.tv_recipe_store);
                                            if (null != tvThumbNum) {
                                                tvThumbNum.setText(NumberUtils.formatNum(recipeHotBean.getFavoriteCount()));
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
//                        favoritResult.setValue(new Result.Error(new Exception(throwable)));
                                        }
                                    });
                        } else {
                            ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                            com.android.baseconfig.R.anim.activity_open_exit)
                                    .navigation(getActivity());
                        }
                    }
                }
            }
        });
        recipeAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (recipeAdapter.getData().size() > position) {

                if (recipeAdapter.getData().get(position).getItemType() == RecipeHotBean.TYPE_ITEM) {
                    RecipeHotBean bean = recipeAdapter.getData().get(position);
                    AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
                } else if (recipeAdapter.getData().get(position).getItemType() == RecipeHotBean.TYPE_LOAD) {
                    ARouter.getInstance().build(PathUrl.PATH_MD_VIDEO_LIST)
                            .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                    com.android.baseconfig.R.anim.activity_open_exit)
                            .navigation(FoodFragment.this.getContext());
                }
            }
        });

        bindingView.rvRecipeList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean isTopVideoShow = true;
            private boolean isFloatSwitchTitleFirstShow = false;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int[] arr = new int[2];
                gridLayoutManager.findFirstCompletelyVisibleItemPositions(arr);
                int indexTmp = findMax(arr);
                Logc.d("foodpage_video_state " + arr[0] + ", " + arr[1]);
                if ((indexTmp == 1 || indexTmp == 2) && mHotList.size() > 0) {
                    hotAdapter.notifyDataSetChanged();
                }
                if (isTopVideoShow && -1 != indexTmp) {
                    recipeAdapter.pauseOnViewHide();
                    isTopVideoShow = false;
                } else if (!isTopVideoShow && -1 == indexTmp) {
                    recipeAdapter.resumeOnViewShow();
                    isTopVideoShow = true;
                }

                if (null != rvRecordLayoutManager && null != recipeAdapter && rvRecordLayoutManager.findFirstCompletelyVisibleItemPosition() < 0) {
                    recipeAdapter.stopListPlay();

                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Logc.d("foodpage_video_state_onScrolled " + dx + ", " + dy);

                changeWithScrollState();
            }
        });

    }


    private void changeWithScrollState() {
        int[] arr = new int[2];
        gridLayoutManager.findFirstCompletelyVisibleItemPositions(arr);

        // int indexTmp = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
        int indexTmp = findMax(arr);
        // int indexTmp = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
        Logc.d("onScrolled " + arr[0] + ", " + arr[1] + "  " + isVisibleLocal(ivXunwei, true));

        if (!isVisibleLocal(ivXunwei, true) && indexTmp == -1) {
            bindingView.rlButtonHead.setVisibility(View.VISIBLE);
        } else if (isVisibleLocal(ivXunwei, true) && indexTmp == -1) {
            bindingView.rlButtonHead.setVisibility(View.GONE);
        }

        if (mHotList.size() > 0) {
            if (indexTmp > 2) {
                bindingView.rlFloatTitleBottom.setVisibility(View.VISIBLE);
            } else if (indexTmp <= 2) {
                bindingView.rlFloatTitleBottom.setVisibility(View.GONE);
            }
        } else {
            if (indexTmp == 1 && isHideShowed) {
                bindingView.rlFloatTitleBottom.setVisibility(View.VISIBLE);
            } else if (indexTmp < 1) {
                bindingView.rlFloatTitleBottom.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 判断View是否可见
     *
     * @param target   View
     * @param judgeAll 为true时,判断View全部可见才返回true
     * @return boolean
     */
    public static boolean isVisibleLocal(View target, boolean judgeAll) {
        Rect rect = new Rect();
        target.getLocalVisibleRect(rect);
        if (judgeAll) {
            return rect.top == 0;
        } else {
            return rect.top >= 0;
        }
    }

    private void initRecycleView() {
        gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        bindingView.rvRecipeList.setLayoutManager(gridLayoutManager);
        //将上部分布局改为headrview
        headerView = getLayoutInflater().inflate(R.layout.food_fragment_head, bindingView.rvRecipeList, false);
        rlNoneResult = getLayoutInflater().inflate(R.layout.item_none_result, bindingView.rvRecipeList, false);
        ivRecipeAll = headerView.findViewById(R.id.iv_recipe_all);
        ivFruitEggs = headerView.findViewById(R.id.iv_fruit_eggs);
        ivMainFood = headerView.findViewById(R.id.iv_main_food);
        ivMeatMean = headerView.findViewById(R.id.iv_meat_mean);
        ivSeaFood = headerView.findViewById(R.id.iv_sea_food);
        tvFruitEggs = headerView.findViewById(R.id.tv_fruit_eggs);
        tvMainFood = headerView.findViewById(R.id.tv_main_food);
        tvMeatMean = headerView.findViewById(R.id.tv_meat_mean);
        tvSeaFood = headerView.findViewById(R.id.tv_sea_food);
        edtFoodInput = headerView.findViewById(R.id.edt_food_input);
        ivScan = headerView.findViewById(R.id.iv_scan);
        rvRecordRecipe = headerView.findViewById(R.id.rv_record_recipe);
        rvRecipeClass = headerView.findViewById(R.id.rv_recipe_class);
        rvRecipeCooker = headerView.findViewById(R.id.rv_recipe_cookers);
        rvRecipeDevice = headerView.findViewById(R.id.rv_recipe_device);
        tvRecipeHot = headerView.findViewById(R.id.tv_recipe_hot);
        tvRecipeNew = headerView.findViewById(R.id.tv_recipe_new);
        llTopicOuter = headerView.findViewById(R.id.ll_topic_outer);
        rlButtonButtom = headerView.findViewById(R.id.rl_button_buttom);
        mHorizontalRefreshLayout = headerView.findViewById(R.id.horizontal_jump_to_info);
        ivXunwei = headerView.findViewById(R.id.iv_xunwei);

        //获取到headerview中的子控件
        bindingView.rvRecipeList.addHeaderView(headerView);
        bindingView.rvRecipeList.setFocusableInTouchMode(false);
        bindingView.rvRecipeList.setFocusable(false);
        //bindingView.rvRecipeList.setHasFixedSize(true);

        initVideoList();
        topicAdapter = new RecipeTopicAdapter(mTopicList, getActivity());
        cookerAdapter = new RecipeChefAdapter(mCookerList, getActivity());
        deviceAdapter = new RecipeDeviceAdapter(mDeviceList, getActivity(), (int position, boolean state) -> {
            deviceAdapter.setPosition(position);
            if (!state) {
                deviceProductModel = mDeviceList.get(position).getModelId();
                bindingView.tvSelectedDevice.setText(mDeviceList.get(position).getModelTypeName());
                DevicePosition = position + 1;
                if (selectDevicePopwindow != null)
                    selectDevicePopwindow.setPopDevicePosition(DevicePosition);
            } else {
                deviceProductModel = "";
                DevicePosition = 0;
                bindingView.tvSelectedDevice.setText(getActivity().getResources().getString(R.string.total_device_recipes));
                if (selectDevicePopwindow != null)
                    selectDevicePopwindow.setPopDevicePosition(DevicePosition);
            }
            originNewPage = 1;
            originHotPage = 1;
            if (StatePositon == 1) {
                initHotRecipe(deviceProductModel);
            } else {
                initNewRecipe(deviceProductModel);
            }
            isHideShowed = false;
        });
        noneResultAdapter = new RecipeNoneResultAdapter(getActivity());
        hotAdapter = new RecipeHotAdapter(mHotList, getActivity());
        hotAdapter.setShowName(true);
        hotAdapter.setUnlike(true);
        hotAdapter.setRecipeHotListener(new RecipeHotAdapter.OnClassifyClickListener() {
            @Override
            public void OnItemClick(int position) {
                RecipeHotBean bean = mHotList.get(position);
                if (AppAgent.h5Debug) {
                    AppAgent.startDebugTiny(activity, Constants.App.PAGE_RECIPE, "",
                            "id=" + bean.getRecipeId());
                } else {
                    AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());
                }
            }

            @Override
            public void OnItemLongClick(int position) {
                Log.e(TAG, "OnItemLongClick");
            }

            @Override
            public void OnAvatarClick(int position) {
                RecipeHotBean hotBean = mHotList.get(position);
                if (!TextUtils.isEmpty(hotBean.getChefId())) {
                    Intent intent = new Intent(getActivity(), CookerHomeActivity.class);
                    intent.putExtra(CHEF_ID, hotBean.getChefId());
                    startActivity(intent);
                } else {
                    ToastUtils.getInstance().showCustomToast(R.string.check_error);
                }
            }

            @Override
            public void OnStarClick(int position) {

                RecipeHotBean bean = mHotList.get(position);
                int state = bean.getFavoriteType();
                if (AppAgent.isLogin()) {
                    if (state == 1) {
                        cancleRecipeStored(bean.getFavoriteId());
                    } else {
                        RecipeStoreBean storeBean = new RecipeStoreBean();
                        storeBean.setAddrId(bean.getRecipeId());
                        storeBean.setFavoriteAddr("RECIPE_ID");
                        setRecipeStored(storeBean);
                    }
                } else {
                    SuporPresenter.getInstance().getCmccHelper().displayLogin(true);
                }
            }

            @Override
            public void OnUnlikeRecipe(int position) {

            }

            @Override
            public void OnUnlikeClassify(int position) {

            }
        });
        //LoadMoreWrapper hotWrapper = new LoadMoreWrapper(hotAdapter);
        bindingView.rvRecipeList.setAdapter(hotAdapter);
        bindingView.rvRecipeList.addItemDecoration(new FoodGridItemDecoration(ContextCompat.getColor(AppAgent.getApp(),
                com.supor.aiot.common.R.color.transparent),
                getResources().getDimensionPixelSize(R.dimen.dp_1),
                getResources().getDimensionPixelSize(R.dimen.dp_1),
                getResources().getDimensionPixelSize(R.dimen.dp_12),
                getResources().getDimensionPixelSize(R.dimen.dp_12), 0));
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getActivity());
        linearLayoutManager2.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeClass.setAdapter(topicAdapter);
        rvRecipeClass.addItemDecoration(new MyItemDecoration(getActivity()));
        rvRecipeClass.setLayoutManager(linearLayoutManager2);

        LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(getActivity());
        linearLayoutManager3.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeDevice.addItemDecoration(new MyItemDecoration(getActivity()));
        rvRecipeDevice.setAdapter(deviceAdapter);
        rvRecipeDevice.setLayoutManager(linearLayoutManager3);

        LinearLayoutManager linearLayoutManager4 = new LinearLayoutManager(getActivity());
        linearLayoutManager4.setOrientation(RecyclerView.HORIZONTAL);
        rvRecipeCooker.setAdapter(cookerAdapter);
        rvRecipeCooker.addItemDecoration(new MyItemDecoration(getActivity()));
        rvRecipeCooker.setLayoutManager(linearLayoutManager4);


        tvRecipeHot.setOnClickListener(this);
        bindingView.tvHeadHot.setOnClickListener(this);
        tvRecipeNew.setOnClickListener(this);
        bindingView.tvHeadNew.setOnClickListener(this);
        bindingView.rvRecipeList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int scrollY;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY += dy;
                int parallaxHeight = getResources().getDimensionPixelOffset(R.dimen.dp_238);
                bindingView.parallax.setTranslationY(-Math.min(scrollY, parallaxHeight));
            }
        });


    }


    private void changeState(int position) {
        StatePositon = position;
        if (position == 0) {
            tvRecipeHot.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            tvRecipeHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            tvRecipeNew.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            tvRecipeNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            tvRecipeNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvRecipeHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvRecipeHot.setDotVisible(false);
            tvRecipeNew.setDotVisible(true);

            bindingView.tvHeadHot.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            bindingView.tvHeadHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            bindingView.tvHeadNew.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            bindingView.tvHeadNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            bindingView.tvHeadNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            bindingView.tvHeadHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            bindingView.tvHeadHot.setDotVisible(false);
            bindingView.tvHeadNew.setDotVisible(true);

            originNewPage = 1;
            initNewRecipe(deviceProductModel);
        } else if (position == 1) {
            tvRecipeNew.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            tvRecipeNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            tvRecipeHot.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            tvRecipeHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            tvRecipeHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvRecipeNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvRecipeHot.setDotVisible(true);
            tvRecipeNew.setDotVisible(false);

            bindingView.tvHeadNew.setTextColor(getActivity().getResources().getColor(R.color.content_assist));
            bindingView.tvHeadNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_14));
            bindingView.tvHeadHot.setTextColor(getActivity().getResources().getColor(R.color.content_default));
            bindingView.tvHeadHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getActivity().getResources().getDimension(R.dimen.sp_17));
            bindingView.tvHeadHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            bindingView.tvHeadNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            bindingView.tvHeadHot.setDotVisible(true);
            bindingView.tvHeadNew.setDotVisible(false);
            originHotPage = 1;
            initHotRecipe(deviceProductModel);
        }
    }

    private void initClassify(String classify) {
        for (int i = 0; i < mOriginList.size(); i++) {
            if (mOriginList.get(i).getClassificationName().equals(classify)) {
                Intent intent = new Intent(getActivity(), RecipeTagsActivity.class);
                intent.putExtra(CLASSIFY_SECOND_DATA, mOriginList.get(i));
                intent.putExtra(CLASSIFY_SECOND_POSITION, 0);
                getActivity().startActivity(intent);
            }
        }
    }

    private void initRecipeClassify(List<ChildListBean> childListBeanList) {

        this.childListBeanList = childListBeanList;

        if (childListBeanList == null || childListBeanList.size() < 4) {
            headerView.findViewById(R.id.ll_recipe_tag_all).setVisibility(View.VISIBLE);
            return;
        }
        ;

        ChildListBean childListBean = childListBeanList.get(0);
        tvMeatMean.setText(childListBean.getClassificationName());
        GlideApp.with(this).load(childListBean.getClassificationImage()).into(ivMeatMean);

        childListBean = childListBeanList.get(1);
        tvMainFood.setText(childListBean.getClassificationName());
        GlideApp.with(this).load(childListBean.getClassificationImage()).into(ivMainFood);

        childListBean = childListBeanList.get(2);
        tvSeaFood.setText(childListBean.getClassificationName());
        GlideApp.with(this).load(childListBean.getClassificationImage()).into(ivSeaFood);

        childListBean = childListBeanList.get(3);
        tvFruitEggs.setText(childListBean.getClassificationName());
        GlideApp.with(this).load(childListBean.getClassificationImage()).into(ivFruitEggs);

        headerView.findViewById(R.id.ll_recipe_tag_all).setVisibility(View.VISIBLE);
    }

    @Override
    public int setContent() {
        return R.layout.food_fragment_root;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_recipe_hot || view.getId() == R.id.tv_head_hot) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            changeState(1);
        } else if (view.getId() == R.id.tv_recipe_new || view.getId() == R.id.tv_head_new) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            changeState(0);
        } else if (view.getId() == R.id.iv_recipe_all) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            Intent intent = new Intent(getActivity(), ClassifyActivity.class);
            intent.putExtra(CLASSIFY_DATA, (Serializable) mClassifyList);
            getActivity().startActivity(intent);
        } else if (view.getId() == R.id.iv_meat_mean) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            if (childListBeanList == null || childListBeanList.size() < 1) {
                initClassify(getActivity().getResources().getString(R.string.meat_mean));
                return;
            }
            initClassify(childListBeanList.get(0).getClassificationName());
        } else if (view.getId() == R.id.iv_main_food) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            if (childListBeanList == null || childListBeanList.size() < 2) {
                initClassify(getActivity().getResources().getString(R.string.main_food));
                return;
            }
            initClassify(childListBeanList.get(1).getClassificationName());
        } else if (view.getId() == R.id.iv_sea_food) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            if (childListBeanList == null || childListBeanList.size() < 3) {
                initClassify(getActivity().getResources().getString(R.string.sea_food));
                return;
            }
            initClassify(childListBeanList.get(2).getClassificationName());
        } else if (view.getId() == R.id.iv_fruit_eggs) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            if (childListBeanList == null || childListBeanList.size() < 4) {
                initClassify(getActivity().getResources().getString(R.string.fruit_eggs));
                return;
            }
            initClassify(childListBeanList.get(3).getClassificationName());
        } else if (view.getId() == R.id.edt_food_input || view.getId() == R.id.iv_head_search) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            Intent intent = new Intent(getActivity(), IntoSearchActivity.class);
            intent.putExtra(RECOMOND_WORD, recomondWord);
            getActivity().startActivity(intent);
        } else if (view.getId() == R.id.iv_scan) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            // gotoScanActivity();
        } else if (view.getId() == R.id.rl_select_device) {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            selectDevicePopwindow = new SelectDevicePopwindow(getActivity());
            selectDevicePopwindow.setDeviceData(mDeviceList);
            // 设置PopupWindow的背景
            selectDevicePopwindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            // 设置PopupWindow是否能响应外部点击事件
            selectDevicePopwindow.setOutsideTouchable(true);
            // 设置PopupWindow是否能响应点击事件
            selectDevicePopwindow.setTouchable(true);
            selectDevicePopwindow.showAsDropDown(bindingView.rlSelectDevice, 0, -36);
            selectDevicePopwindow.setPopDevicePosition(DevicePosition);
            selectDevicePopwindow.setPopDeviceListener((position, typeID, deviceType) -> {
                if (!TextUtils.isEmpty(deviceType))
                    bindingView.tvSelectedDevice.setText(deviceType);
                deviceProductModel = typeID;
                originNewPage = 1;
                originHotPage = 1;
                if (StatePositon == 1) {
                    initHotRecipe(deviceProductModel);
                } else {
                    initNewRecipe(deviceProductModel);
                }
                DevicePosition = position;
                selectDevicePopwindow.setPopDevicePosition(DevicePosition);
                if (position == 0) {
                    deviceAdapter.clearAll();
                } else {
                    deviceAdapter.setPositionDevice(position - 1);
                }
                isHideShowed = true;
            });
            bindingView.ivSelectedState.setImageResource(R.mipmap.ic_black_up);
            selectDevicePopwindow.setOnDismissListener(() -> {
                bindingView.ivSelectedState.setImageResource(R.mipmap.ic_black_down);
            });
        }
    }

    @Override
    public void onPause() {
        super.onPause();
//        if (null != videoScrollPlayerManager) {
//            videoScrollPlayerManager.onPause();
//        }
        if (null != recipeAdapter) {
            if (null != rvRecordRecipe) {
                rvRecordRecipe.removeCallbacks(videoResumeRun);
            }
            recipeAdapter.onPause();
        }
    }

    @Override
    protected void onRefresh() {
        super.onRefresh();
        initOriginState();
    }

    private boolean videoRunIsAlive = false;
    private Runnable videoResumeRun = new Runnable() {
        @Override
        public void run() {
            if (null != recipeAdapter /*&& videoRunIsAlive*/) {
                recipeAdapter.onResume();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
//        if (null != videoScrollPlayerManager) {
//            videoScrollPlayerManager.onResume();
//        }
//        bindingView.food.smoothScrollTo(0,0);
        MPLoggerUtils.homeFoodPageCount();
        startPlay();
        int nettype = NetObserverManager.getInstance().getCurrentNetType();
        if (nettype != -1 && nettype != 0 && nettype != 1) {
            ToastUtils.getInstance().showCustomToast(getActivity().getResources().getString(R.string.no_wifi_notice));
        }
    }

    private void startPlay() {
        if (!isFirstShow && null != recipeAdapter && null != gridLayoutManager) {
            int[] arr = new int[2];
            gridLayoutManager.findFirstCompletelyVisibleItemPositions(arr);
            // int indexTmp = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
            int indexTmp = findMax(arr);
            // int indexTmp = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
            if (indexTmp == -1) {
                if (null != rvRecordRecipe) {
                    rvRecordRecipe.removeCallbacks(videoResumeRun);
                    rvRecordRecipe.postDelayed(videoResumeRun, 150);
                }
            }
        }
    }

    boolean isFirstShow = true;

    public void initShow() {
        isFirstShow = false;
        getVideoRecipeData();
//        startPlay();
    }

    /**
     * 取数组中最大值
     *
     * @param lastPositions
     * @return
     */
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }

        return max;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        RxBus3.getInstance().unregister(this.getClass());
    }

    private long lastClick;

    /**
     * [防止快速点击]
     *
     * @return
     */
    public boolean passClick() {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }
}
